package br.com.ecommerce.converter;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.suricattus.surispring.framework.domain.Entity;



@FacesConverter("entityConverterGeral")
public class EntityConverterGeral implements Converter {

	public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
		if (value != null) {
			return this.getAttributesFrom(component).get(value);
		}
		return null;
	}

	public String getAsString(FacesContext ctx, UIComponent component, Object value) {

		if (value != null
				&& !"".equals(value)) {

			Entity entity = (Entity) value;

			if (entity.getIdentifier() != null) {
			    this.addAttribute(component, entity);
				return String.valueOf(entity.getIdentifier());
			}
		}

		return null;
	}

	protected void addAttribute(UIComponent component, Entity o) {
		String key = o.getIdentifier().toString();
		this.getAttributesFrom(component).put(key, o);
	}

	protected Map<String, Object> getAttributesFrom(UIComponent component) {
		return component.getAttributes();
	}

}